package cn.xuewenbao.edu.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecg.modules.oss.service.IOSSFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


/**
 * @Auther: mafayu
 */
@RestController
@RequestMapping("/edu/file")
@Api(tags = "文件上传")
@Slf4j
public class FileController {

    @Value("${jeecg.oss.endpoint}")
    private String endpoint;

    @Value("${jeecg.oss.accessKey}")
    private String accessKeyId;

    @Value("${jeecg.oss.secretKey}")
    private String accessKeySecret;

    @Value("${jeecg.oss.bucketName}")
    private String bucketName;

    @Autowired
    private IOSSFileService ossFileService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @ApiOperation(value = "文件本地上传, 到platform/{jeecg.path.upload}, 与platform/db同级")
    @PostMapping("/upload")
    public Result<?> upload(HttpServletRequest request) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        if (oConvertUtils.isEmpty(bizPath)) {
            bizPath = "";
        }
        //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
        savePath = this.uploadLocal(file, bizPath);

        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }

    @ApiOperation(value = "文件上传, 阿里OSS")
    @PostMapping(value = "/uploadOSS")
    public Result<?> uploadMinio(HttpServletRequest request) {
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        if (oConvertUtils.isEmpty(bizPath)) {
            bizPath = "upload";
        }
        savePath = CommonUtils.upload(file, bizPath, "alioss");
        if (oConvertUtils.isNotEmpty(savePath)) {
            return Result.ok(savePath);
        } else {
            return Result.error(savePath);
        }
    }

    @ApiOperation(value = "删除oss文件")
    @PostMapping(value = "deleteOss")
    public Result<?> deleteOss(@RequestBody String url) {
        Result<?> result = new Result<>();
        String newBucket = bucketName;
        String bucketUrl = "";

        bucketUrl = "http://" + newBucket + "." + endpoint + "/";
        url = url.replace(bucketUrl, "");

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.deleteObject(newBucket, url);

        result.setSuccess(true);
        result.setMessage("文件删除成功");
        return result;
    }

    private String uploadLocal(MultipartFile mf, String bizPath) {
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);
            String dbpath = null;
            if (oConvertUtils.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    @GetMapping("path")
    @ApiOperation(value = "路径")
    public String getPath() {
        return this.getClass().getResource("/").getPath();
    }
}
